package com.esteel.settlement.config.pa;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import com.esteel.settlement.config.validator.PacketValidator;
import com.esteel.settlement.config.validator.ValidatorResult;
import com.esteel.settlement.pa.packet.PaPacket;

/**
 * 用于执行调用平安B2Bic http接口的公共类
 * @author zhangxiuzhi
 *
 */

public class PaTemplate {
	
	private final RestTemplate restTemplate = restTemplate();
	
	@Autowired
	private PacketValidator packetValidator;
	
	private Logger logger =  LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 用于记录消息
	 */

	
	@Value("${pa.url}")
	private String paUrl ;
	
	private RestTemplate restTemplate(){

		RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();

		RestTemplate paTemplate = restTemplateBuilder.build();
		
		paTemplate.getMessageConverters().clear();
		paTemplate.getMessageConverters().add(new PaHttpMessageConverter());
		return paTemplate;
		
	}
	

	public <T> T execute(PaPacket packet,Class<T> responseType){
		
		//判断传入的类必须是PaPacket的超类
		Assert.isTrue(PaPacket.class.isAssignableFrom(responseType));
		
		logger.info(packet.marshal());
			
		//验证业务报问题是否符合规范
		ValidatorResult<PaPacket> result = packetValidator.validator(packet);
		Assert.isTrue(result.isValid(),result.getMessage());
		

		HttpHeaders tempHeaders = new HttpHeaders();
		tempHeaders.add("Content-type", "application/json");
		HttpEntity<PaPacket> httpEntity = new HttpEntity<PaPacket>(packet,tempHeaders);

		 T response = restTemplate.postForObject(paUrl, httpEntity, responseType);
		 
		 PaPacket rsp = (PaPacket)response;
		 logger.info(rsp.marshal());
	 

		 return response;
	}
	
	
}
